const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");
// 要派的单据查询
router.post('/receipt/pdsk', async ctx => {
    let user = ctx.user
    let tenantId = user.tenantId;
    let formData = ctx.request.body.formData;
    let endDate = formData.endDate?formData.endDate:tool.getDay('', -1);
    let salesId = formData.salesId?formData.salesId:0
    let buId = formData.buId?formData.buId:0
    let billNo = formData.billNo?formData.billNo:''
    let contactCatId = formData.contactCatId?formData.contactCatId:0
    let invId = formData.invId?formData.invId:0
    let exceptPdBill = formData.exceptPdBill?formData.exceptPdBill:0
    let goodCatId = formData.goodCatId?formData.goodCatId:0;

    let sql = `
                with bills as (select id,
                          tenantId,
                          billNo,
                          transType,
                          transTypeName,
                          billStateName,
                          billDate,
                          salesId,salesName,
                          buId,buName,
                          contactCatName,
                          arrearsReal,
                          arrearsReal - (hxAmount + yhAmount) leftAmount
                   from v_main_withhx
                   where tenantId = ${tenantId} and billType in('SALE','YS') and billState='accounted' 
                     and billDate <= '${endDate}'
                     and (buId = ${buId} or ${buId} = 0)
                     and (salesId = ${salesId} or ${salesId} = 0)
                     and (billNo like '%${billNo}%' or '${billNo}' = '')
                     and (salesId = ${salesId} or ${salesId} = 0)
                     and (contactCatId = ${contactCatId} or ${contactCatId} = 0)
               )
                select distinct a.id, a.tenantId, a.billNo,a.transType, transTypeName, billStateName, billDate, salesId,salesName,buId, buName,contactCatName, arrearsReal,leftAmount,rp.state
                from bills a left join v_main_info b on a.tenantId=b.tenantId and a.id=b.iid
                left join (select id,state,tenantId,billId from receipt_pd where tenantId=${tenantId} and state=N'收款中') rp on a.tenantId=rp.tenantId and a.id=rp.billId
                where a.tenantId=${tenantId} and a.leftAmount<>0 
    `

    if(exceptPdBill) {
        sql += ` and a.leftAmount<>0  and rp.id is null  `
    }
    if(invId) {
        sql += ` b.invId=${invId} `
    }
    if(goodCatId) {
        let code = await db.models['goodsCat'].findOne({
            where: {
                id: goodCatId,
                tenantId
            }
        })
        if(code && code.code) {
            sql += ` and b.goodCatCode like '${code.code}%' `
        }
    }
    sql += ' order by  buName,billDate '
    let list = await db.query(sql, {type: QueryTypes.SELECT})
    if(list.length === 0) return ctx.err('没有找到符合条件的票据')
    return ctx.suc('', {total: list.length, list})

})
// 扫单据找票据
router.post('/receipt/pdskscan', async ctx => {
    let user = ctx.user
    let tenantId = user.tenantId;
    let formData = ctx.request.body;
    let billId = formData.billId
    let model = await db.models['invoice'].findOne({
        where: {
            tenantId,
            id: billId
        }
    })
    let buId = model.buId;

    let sql = `
                with bills as (select id,
                          tenantId,
                          billNo,transType,
                          transTypeName,
                          billStateName,
                          billDate,
                          salesId,salesName,
                          buId,buName,
                          contactCatName,
                          arrearsReal,
                          arrearsReal - (hxAmount + yhAmount) leftAmount
                   from v_main_withhx
                   where tenantId = ${tenantId} and billType in('SALE','YS') and billState='accounted' and id=${billId} 
               )
                select distinct a.id, a.tenantId, billNo, transType,transTypeName, billStateName, billDate,salesId, salesName,buId, buName,contactCatName, arrearsReal,leftAmount 
                from bills a  
                where a.tenantId=${tenantId}  and leftAmount<>0 and a.id=${billId} 
       `
    let list = await db.query(sql, {type: QueryTypes.SELECT, plain: true})
    if(!list) return ctx.err('未找到票据，或已核销完')
    let sql1 = `
                with bills as (select id,
                          tenantId,
                          billNo,transType,
                          transTypeName,
                          billStateName,
                          billDate,
                          salesId,salesName,
                          buId,buName,
                          contactCatName,
                          arrearsReal,
                          arrearsReal - (hxAmount + yhAmount) leftAmount
                   from v_main_withhx
                   where tenantId = ${tenantId} and transType=150602 and billState='accounted' and buId=${buId}
               )
                select distinct a.id, a.tenantId, billNo, transType,transTypeName, billStateName, billDate,salesId, salesName,buId, buName,contactCatName, arrearsReal,leftAmount 
                from bills a  
                where a.tenantId=${tenantId}  and leftAmount<>0  
       `
    let tulist = await db.query(sql1, {type: QueryTypes.SELECT})
    // 是否在派单中
    let has = await db.models['receiptPd'].findOne({
        where: {
            tenantId,
            billId: list.id,
            state: '收款中'
        }
    })
    if(has) {
        return ctx.err(`单据正在收款中,于 ${has.createdAt} 指派于  ${has.doName} `)
    }

    return ctx.suc('', {
        list,
        tuiList: tulist
    })

})

module.exports = router;
